package com.example.myapplication.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.network.api.Category
import com.example.myapplication.network.api.CategoryApiService
import com.example.myapplication.network.core.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class CategoryViewModel : ViewModel(){
    private val _categoriesState = MutableStateFlow<NetworkResult<List<Category>>>(NetworkResult.Loading())
    val categoriesState = _categoriesState.asStateFlow()

    init {
        getCategories()
    }

    fun getCategories(){
        viewModelScope.launch {
            _categoriesState.value = NetworkResult.Loading()
            try {
                val categories = CategoryApiService.getInstance().getCategories()
                //println("分类数据："+categories)
                _categoriesState.value = NetworkResult.Success(categories)
            }catch (e: Exception){
                _categoriesState.value = NetworkResult.Error("分类数据获取失败...")
            }
        }
    }
}